import base64
# from DrissionPage import ChromiumPage
import os
import requests
import time
import allure
import json
import yaml
from common import get_alter
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

class Auto_code(object):

    # def __init__(self):
    #     self.url = 'https://www.bilibili.com/'
    #     # 浏览器驱动对象
    #     self.page = ChromiumPage()

    # def parse_login(self):
    #     self.page.get(self.url)
    
    # 图片识别并返回坐标
    # 原图
    def verify_b(self,text):

        with open(r'D:\git_zhaol\pytest\bilibili_pytest\verif_code.png', 'rb') as f:
            b_png = base64.b64encode(f.read()).decode()  ## 图片二进制流base64字符串
        url = "http://api.jfbym.com/api/YmServer/customApi"
        data = {
            ## 关于参数,一般来说有3个;不同类型id可能有不同的参数个数和参数名,找客服获取
            "token": "fdYVUjlbpMJMFO5Wgr0XEaB3A0UJd1SdWBtQ4NbfFXk",
            "type": "300010",
            "image": b_png,
            "extra": text
        }
        _headers = {
            "Content-Type": "application/json"
        }
        response = requests.request("POST", url, headers=_headers, json=data).json()
        return response.get('data')['data']
    # 截图-顶部打标顺序
    def verify_h(self):
        with open(r'D:\git_zhaol\pytest\bilibili_pytest\verif_code_heed.png', 'rb') as f:
            b_png = base64.b64encode(f.read()).decode()  ## 图片二进制流base64字符串
        url = "http://api.jfbym.com/api/YmServer/customApi"
        data = {
            ## 关于参数,一般来说有3个;不同类型id可能有不同的参数个数和参数名,找客服获取
            "token": "fdYVUjlbpMJMFO5Wgr0XEaB3A0UJd1SdWBtQ4NbfFXk",
            "type": "10115",
            "image": b_png
        }
        _headers = {
            "Content-Type": "application/json"
        }
        response = requests.request("POST", url, headers=_headers, json=data).json()
        hanzi = response.get('data')['data']
        hanzi = ','.join(hanzi[7:])
        return hanzi

    # 全图-人工接口
    def verify_full(self,path):
        with open(path, 'rb') as f:
            b = base64.b64encode(f.read()).decode()  # 图片二进制流base64字符串
        url = "http://api.jfbym.com/api/YmServer/customApi"
        data = {
            ## 关于参数,一般来说有3个;不同类型id可能有不同的参数个数和参数名,找客服获取
            "token": "fdYVUjlbpMJMFO5Wgr0XEaB3A0UJd1SdWBtQ4NbfFXk",
            "type": "30009",
            "image": b,
        }
        _headers = {
            "Content-Type": "application/json"
        }
        response = requests.request("POST", url, headers=_headers, json=data).json()
        res = response.get('data')['data']
        return res
    def auto_click(self,selenium,captcha_full, coord_data):
        """
        根据提供的坐标数据点击验证码图片
        
        Args:
            driver: Selenium WebDriver实例
            image_element: 验证码图片的WebElement
            coord_data: 坐标数据字符串，格式如 '171,188|276,60|68,134|130,284'
        """
        # 解析坐标数据
        coord_pairs = coord_data.split('|')
        actions = ActionChains(selenium)
        center_point = 155
        for pair in coord_pairs:
            x, y = map(int, pair.split(','))
            actions.move_to_element_with_offset(captcha_full,xoffset=0, yoffset=0).perform()
            actions.move_by_offset(x-160,y-205).click().perform()
         
    # 登录脚本
    def login_on(self,selenium,name,password,claim):
        selenium.find_element(by=By.CSS_SELECTOR, value='div.header-login-entry').click()
        selenium.find_element(by=By.CSS_SELECTOR, value="input[placeholder='请输入账号']").send_keys(name)
        selenium.find_element(by=By.CSS_SELECTOR, value="input[placeholder='请输入密码']").send_keys(password)
        selenium.find_element(by=By.CSS_SELECTOR, value=".btn_primary").click()
        if not os.path.exists(r'D:\git_zhaol\pytest\bilibili_pytest\picture'):
            os.mkdir(r'D:\git_zhaol\pytest\bilibili_pytest\picture')
        captcha_full = WebDriverWait(selenium, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR,'.geetest_holder.geetest_silver')))
        captcha_full.screenshot(r'D:\git_zhaol\pytest\bilibili_pytest\picture\play_login.png')
        
        post_data = self.verify_full(r'D:\git_zhaol\pytest\bilibili_pytest\picture\play_login.png')
        self.auto_click(selenium, captcha_full, post_data)
        time.sleep(0.5)
        
        # 点击确定验证码
        certain_b = selenium.find_element(By.CSS_SELECTOR, 'a.geetest_commit')
        certain_b.click()
        time.sleep(0.5)
        # 获取弹窗
        toast_text = get_alter.get_toast_text(selenium,claim)
        time.sleep(5)
        with allure.step("验证结果"):
            assert  claim in toast_text
    # 保存cookie
    def save_cookie(self,selenium):
        cookies = selenium.get_cookies()
        with open(r'D:\git_zhaol\pytest\bilibili_pytest\test_data\cookies.json','w',encoding='utf-8') as f:
            f.write(json.dumps(cookies))
    # 读取cookie
    def load_cookie(self,selenium):
        with open(r'D:\git_zhaol\pytest\bilibili_pytest\test_data\cookies.json','r',encoding='utf-8') as f:
           cookies = json.loads(f.read())
        # 清除旧Cookie（可选）
        selenium.delete_all_cookies()
        # 逐个添加Cookie
        for cookie in cookies:
            selenium.add_cookie(cookie) 
        # 刷新页面，使Cookie生效
        selenium.refresh()

    # yaml数据读取
    def load_data(path):
        with open(path, 'r', encoding='utf-8') as f:
            test_data = yaml.load(f, Loader=yaml.SafeLoader)
            return test_data


if __name__ == '__main__':
    auto_c = Auto_code()
    text = auto_c.verify_h()

